package com.chcit.mobile.mvp.shipment.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.textfield.TextInputEditText;
import androidx.core.widget.NestedScrollView;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding3.widget.RxTextView;
import com.jakewharton.rxbinding3.widget.TextViewEditorActionEvent;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.dialog.DialogPlus;
import com.chcit.custom.view.dialog.ViewHolder;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerDispensingComponent;
import com.chcit.mobile.di.module.DispensingModule;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.RecipeBean;
import com.chcit.mobile.mvp.shipment.adapter.DispensingAdapter;
import com.chcit.mobile.mvp.shipment.contract.DispensingContract;
import com.chcit.mobile.mvp.shipment.presenter.DispensingPresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 发药页面
 */
public class DispensingFragment extends ScanFragment<DispensingPresenter> implements DispensingContract.View {
    protected static final float FLIP_DISTANCE = 50;

    @BindView(R.id.tiet_dispensing_realLocator)
    SuperInputEditText tietRealLocator;
     @BindView(R.id.ll_dispensing_basketCode)
     LinearLayoutCompat llBasketCode;
    @BindView(R.id.tiet_dispensing_pointLocator)
    TextInputEditText tietPointLocator;
    @BindView(R.id.tiet_dispensing_basketCode)
    SuperInputEditText tietBasketCode;
    @BindView(R.id.tv_dispensing_qty)
    TextView tvQty;
    @BindView(R.id.tv_dispensing_unit)
    TextView tvUnit;
    @BindView(R.id.tv_dispensing_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R.id.rv_dispensing_list)
    RecyclerView mRecyclerView;
    private LinearLayout llOdd;
    private DispensingAdapter mAdapter;
    protected List<RecipeBean> unRecipeBeans;
    private List<RecipeBean> doneRecipeBeans;
    private RecipeBean mRecipeBean;
    private DialogPlus dialog;
    private TextView tv;
    protected MenuTypeEnum type;
    TextView tvDate;
    AppCompatEditText etLot;
    private Disposable lotDisposable;
    protected String preNo;


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDispensingComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .dispensingModule(new DispensingModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dispensing, container, false);
    }

    GestureDetector mDetector;

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
     /*   viewPager.setAdapter(new FragmentAdapter(getChildFragmentManager(), fragments));
        //要设置到viewpager.setAdapter后才起作用
        viewPager.setCurrentItem(TabFragmentIndex.TAB_BOOK_LITERATURE_INDEX);
        tlTabs.setupWithViewPager(viewPager);
        tlTabs.setVerticalScrollbarPosition(TabFragmentIndex.TAB_BOOK_LITERATURE_INDEX);*/
        if(type!=null&&type.equals(MenuTypeEnum.PRESCRIPTION_SHIPMENT)){
            llBasketCode.setVisibility(View.VISIBLE);
        }
        mCommonToolbar.getLeftMenuView(0)
                .setOnClickListener(
                        v->{
                            if(mAdapter.getData().size()>0){
                                new MaterialDialog.Builder(getContext())
                                        .title("提示")
                                        .content("该次任务还没完成，确定要返回吗？")
                                        .negativeText("确定")
                                        .positiveText("取消")
                                        .onNegative((dialog, which) -> {
                                            dialog.dismiss();
                                            pop();
                                        })
                                        .build()
                                        .show();
                            }else{
                                pop();
                            }
                        }
                );
        mDetector = new GestureDetector(getContext(), new GestureDetector.OnGestureListener() {

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {

            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                if (e1.getX() - e2.getX() > FLIP_DISTANCE) {
                    //向左滑.
                    if (tlTabs.getSelectedTabPosition() != 0) {
                        tlTabs.getTabAt(0).select();
                    }
                    return true;
                }
                if (e2.getX() - e1.getX() > FLIP_DISTANCE) {
                    if (tlTabs.getSelectedTabPosition() != 1) {
                        tlTabs.getTabAt(1).select();
                    }
                    return true;
                }
                if (e1.getY() - e2.getY() > FLIP_DISTANCE) {
                    //up
                    return true;
                }
                if (e2.getY() - e1.getY() > FLIP_DISTANCE) {

                    return true;
                }
                return false;
            }

            @Override
            public boolean onDown(MotionEvent e) {

                return false;
            }
        });
         nsv.setOnTouchListener((v, event) -> mDetector.onTouchEvent(event));

    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(getContext());
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
         XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    View.OnClickListener dateOnClickListener = new View.OnClickListener() {
        Calendar calendar = Calendar.getInstance();
        @Override
        public void onClick(View v) {
            TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s -> {
                tvDate.setText(s);
            }, 0, calendar);

        }
    };

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(dialog.isShowing()){
            if(etLot!=null){
                etLot.setText(barcodeData);
            }
            return;
        }
         if(type!=null&&type.equals(MenuTypeEnum.PRESCRIPTION_SHIPMENT)&&tietBasketCode.isEnabled()){
             String regex = "^[K][K].*";

            if( Pattern.matches(regex,barcodeData)){
                tietBasketCode.setText(barcodeData);
                tietRealLocator.requestFocus();
                tietBasketCode.setEnabled(false);
                return;
            }else {
                tietBasketCode.setEnabled(false);
            }

        }
         if (mRecipeBean != null && tlTabs.getSelectedTabPosition() == 0) {
            tietRealLocator.setText(barcodeData);
            String info = getResources().getString(R.string.dispensing_confrim_info);
            String infoValue = String.format(info, mRecipeBean.getProductName(), mRecipeBean.getQty());
            tv.setText(infoValue);
            View llDate = dialog.findViewById(R.id.ll_dialog_dispensing_date);
            if ("Y".equals(mRecipeBean.getIsOdd())) {
                llOdd.setVisibility(View.VISIBLE);
                tvDate = dialog.findViewById(R.id.tv_diolog_guaranteeDate);
                AppCompatImageView imageView = dialog.findViewById(R.id.image_dialog_deal);
                llDate.setVisibility(View.VISIBLE);
                tvDate.setText(TimeDialogUtil.getBeforeMonth(0));
                tvDate.setOnClickListener(dateOnClickListener);
                imageView.setOnClickListener(dateOnClickListener);
                llDate.setOnClickListener(dateOnClickListener);

            } else {
                llOdd.setVisibility(View.GONE);
            }

            if (mRecipeBean.getLocatorValue() != null && mRecipeBean.getLocatorValue().equals(barcodeData)) {
                if ("Y".equals(mRecipeBean.getIsOdd())) {
                    dialog.show();
                } else {
                    doConfirm();
                }
            } else {
                new MaterialDialog.Builder(mContext)
                        .content("拣货货位与指示货位不符，是否继续？")
                        .title("提示")
                        .positiveText("确认")
                        .negativeText("取消")
                        .onPositive((dialog, which) -> {
                            dialog.dismiss();
                            this.dialog.show();
                        })
                        .show();

            }
        }
    }

    private void initDialog() {
        dialog = DialogPlus.newDialog(getContext())
                .setContentHolder(new ViewHolder(R.layout.dialog_dispensing))
                //.setExpanded(true)  // This will enable the expand feature, (similar to android L share dialog)
                .setGravity(Gravity.BOTTOM | Gravity.END)
                .setCancelable(false)
                .create();

        Button ok = dialog.findViewById(R.id.dialog_dispensing_ok);
        tv = dialog.findViewById(R.id.tv_dialog_dispensing_detail);
        Button canel = dialog.findViewById(R.id.dialog_dispensing_cancel);
        llOdd = dialog.findViewById(R.id.ll_dialog_dispensing_isObb);
        etLot = dialog.findViewById(R.id.et_dialog_dispensing_lot);
        ok.setOnClickListener(v -> {
            if (llOdd != null && llOdd.isShown()) {
                if (etLot != null && etLot.getText().toString().isEmpty()) {
                    Toast toast = Toast.makeText(mContext, "批号不能为空", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER,0,0);
                    toast.show();
                    return;
                }
            }
            dialog.dismiss();
            doConfirm();
        });
        canel.setOnClickListener(v -> {
            dialog.dismiss();
        });
        lotDisposable = RxTextView.editorActionEvents(etLot)
                .subscribe(new Consumer<TextViewEditorActionEvent>() {
                    @Override
                    public void accept(TextViewEditorActionEvent textViewEditorActionEvent) throws Exception {
                        String text = Objects.requireNonNull(etLot.getText()).toString();
                        if(!text.isEmpty()){
                            hideSoftInput();
                        }

                    }
                });
    }
   /* String text = Objects.requireNonNull(etLot.getText()).toString();
    //判断up状态
                    if (keyEvent!=null&&keyEvent.get() == KeyEvent.KEYCODE_ENTER  && !text.isEmpty()) {
        try {
            hideSoftInput();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
    private void doConfirm() {
        if (mRecipeBean != null) {
          /*  1、	PresNo
            2、	ProductCode
            2、	LocatorValue
            2、	LocatorValue2*/
            JSONObject params = new JSONObject();
            String method = HttpMethodContains.DISPENSING_OK;
            if (type != null) {
                method = HttpMethodContains.DOCUTOR_DISPENSING_OK;
             /*   1、	applyID
                2、	productSpecID productSpecID
                3、	Lot
                4、	GuaranteeDate*/
                params.put("documentNo", mRecipeBean.getDocumentNo());//任务
                params.put("productSpecID", mRecipeBean.getProductSpecID()); //拣货数量
                if (tvDate != null) {
                    params.put("guaranteeDate", tvDate.getText().toString());
                    params.put("lot", etLot.getText().toString());
                }

            } else {
//                if(tietBasketCode.getText().length()<=0){
//                    DialogUtil.showErrorDialog(mContext,"必须绑定框码");
//                    return;
//                }
                params.put("presID", mRecipeBean.getPresID());//任务
                params.put("basketCode",tietBasketCode.getText());//任务
                params.put("presLineID", mRecipeBean.getPresLineID()); //拣货数量
                params.put("pickListId", mRecipeBean.getPresLineID());
                if (llOdd.getVisibility()==View.VISIBLE) {
                    params.put("guaranteeDate", tvDate.getText().toString());
                    params.put("lot", etLot.getText().toString());
                }
            }

            //确认拣货
            mPresenter.doConfirm(method, params, () -> {
                mAdapter.remove(mAdapter.getChekedPosition());
                if (llOdd.getVisibility()==View.VISIBLE) {
                    etLot.setText("");
                }
                if (mAdapter.getData().size() == 0) {
                    SnackbarUtils.Short(getView(), "该任务已完成！即将关闭")
                            .setCallback(new Snackbar.Callback() {
                                @Override
                                public void onDismissed(Snackbar snackbar, int event) {
                                    super.onDismissed(snackbar, event);
                                    pop();
                                }

                                @Override
                                public void onShown(Snackbar snackbar) {
                                    super.onShown(snackbar);

                                }
                            })
                            .gravityFrameLayout(Gravity.CENTER).show();
                    return;
                }
                tietBasketCode.setEnabled(false);
                tietRealLocator.setText("");
                tietRealLocator.requestFocus();
                if (mAdapter.getData().size() <= mAdapter.getChekedPosition()) {
                    mAdapter.setCheckedPosition(0);
                    mAdapter.getOnItemClickListener().onItemClick(mAdapter, null, 0);

                } else {
                    mAdapter.getOnItemClickListener().onItemClick(mAdapter, null, mAdapter.getChekedPosition());
                }
                //tietPointLocator.setText(unRecipeBeans.get(0).getLocatorValue());
            });
        }
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();
        initRecyclerView();
        initDialog();
    }


    private void initRecyclerView() {
        mAdapter = new DispensingAdapter(unRecipeBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position >= 0 && adapter.getData().size() > position) {
                    mAdapter.setCheckedPosition(position);
                    mRecipeBean = (RecipeBean) adapter.getData().get(position);
                    //tietPointLocator.setText(mRecipeBean  .getLocatorValue());
                    if (tlTabs.getSelectedTabPosition() == 1) {
                        if(mRecipeBean.getLocatorValue()!= null){
                            tietRealLocator.setText(mRecipeBean.getLocatorValue());
                        }
                        //tietPointLocator.setEnabled(false);
                    } else {
                        tietPointLocator.setText("");
                       // tietPointLocator.setEnabled(true);
                    }
                    updateClickItemData();
                }

            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.getOnItemClickListener().onItemClick(mAdapter, null, 0);
    }

    /**
     * 更新点击后，在货位下显示的数据
     */
    private void updateClickItemData() {
        if(mRecipeBean != null){
            tvQty.setText(mRecipeBean.getQty());
            tvUnit.setText(mRecipeBean.getUnit());
            tvManufacturer.setText(mRecipeBean.getManufacturer());
        }else{
            tvQty.setText("");
            tvUnit.setText("");
            tvManufacturer.setText("");
        }

    }

    private void getData() {

        JSONObject data = new JSONObject();
               /* start:0
                limit:25
                bpartnerID:1019706
                showLot:true
                appSessionID:1541585528858.6*/
        String method = null;
        if (StringUtils.isNotEmpty(preNo)) {
            switch (type){
                case PRESCRIPTION_SHIPMENT:
                    data.put("presNo", preNo);
                    method = HttpMethodContains.DISPENSING_QUERY;
                    break;
                case DOCUTOR_ADVICE_SHIPMNET:
                    data.put("documentNo", preNo);
                    method = HttpMethodContains.DOCUTOR_DISPENSING_QUERY;
                    break;
            }

            switch (tlTabs.getSelectedTabPosition()) {
                case 0:
                    tietRealLocator.setText("");
                    data.put("status", "N");
                    mPresenter.getData(method, data, list -> {
                        unRecipeBeans = list;
                        mAdapter.addData(list);
                        if (list.size() == 0) {
                            showMessage("没有查询到数据！");
                        } else {
                            tietRealLocator.requestFocus();
                            mRecipeBean = unRecipeBeans.get(0);
                            tietPointLocator.setText(mRecipeBean.getLocatorValue());
                            mAdapter.getOnItemClickListener().onItemClick(mAdapter, null, 0);
                        }
                    });
                    break;
                case 1:
                    data.put("status", "Y");
                    mPresenter.getData(method, data, list -> {
                        if (list.size() == 0) {
                            showMessage("没有查询到数据！");
                        }
                        doneRecipeBeans = list;
                        mAdapter.addData(list);
                        mRecipeBean = null;
                        if (doneRecipeBeans.size() > 0) {
                            mAdapter.getOnItemClickListener().onItemClick(mAdapter, null, 0);
                            tietPointLocator.setText(doneRecipeBeans.get(0).getLocatorValue());
                            tietRealLocator.setText(doneRecipeBeans.get(0).getLocatorValue());
                        }
                    });
                    break;
            }
        }
    }

    Disposable disposable;
    Disposable localDisposable;
    private void initEvent() {
        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mAdapter.getData().clear();
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        disposable = RxTextView.editorActionEvents(tietBasketCode)
                .subscribe(textViewEditorActionEvent -> {
            String text = Objects.requireNonNull(tietBasketCode.getText()).toString();
           if (textViewEditorActionEvent.getActionId() == KeyEvent.KEYCODE_ENDCALL&&!text.isEmpty()){
                onBarcodeEventSuccess(text);
            }
        });
        localDisposable = RxTextView.editorActionEvents(tietRealLocator)
                .subscribe(textViewEditorActionEvent -> {
                    String text = Objects.requireNonNull(tietRealLocator.getText()).toString();
                    //判断up状态
                    if (textViewEditorActionEvent.getActionId() == KeyEvent.KEYCODE_ENDCALL&&!text.isEmpty()){
                            onBarcodeEventSuccess(text);
                    }
                });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
        if(localDisposable!=null){
            localDisposable.dispose();
        }

    }

    @Override
    public boolean onBackPressedSupport() {
        super.onBackPressedSupport();
        return false;
    }
}
